package com.iptv.grape.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;

import androidx.core.content.FileProvider;

import com.iptv.grape.BuildConfig;
import com.iptv.grape.RunTimeApplication;
import com.iptv.grape.beans.ApkBean;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ApkUtil {
    /****
     * 通过获取某个应用信息并捕获未安装时的异常判断
     * @param context
     * @param pkgName
     * @return
     */
    public static boolean isInstallApp(Context context, String pkgName) {
        if (pkgName == null || pkgName.isEmpty()) {
            return false;
        }
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(pkgName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
        }
        if (packageInfo == null) {
            return false;
        } else {
            return true;//true为安装了，false为未安装
        }
    }

    /***
     * 通过获取应用列表对比判断
     * @param context
     * @param pkgName
     * @return
     */
    private boolean isInstallApp2(Context context, String pkgName) {
        if (pkgName == null || pkgName.isEmpty()) {
            return false;
        }
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> info = packageManager.getInstalledPackages(0);
        if (info == null || info.isEmpty())
            return false;
        for (int i = 0; i < info.size(); i++) {
            if (pkgName.equals(info.get(i).packageName)) {
                return true;
            }
        }
        return false;
    }


    /***
     * 安装APK
     * @param act
     * @param path
     */
    public static void installApk(Activity act, String path) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            File file = new File(path);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                String authority = BuildConfig.APPLICATION_ID + ".fileProvider";
                Uri fileUri = FileProvider.getUriForFile(act.getApplicationContext(), authority, file);
                intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            act.startActivityForResult(intent, 0);
        } catch (Exception e) {
            // todo 安装失败的操作
        }

    }


    public static List<ApkBean> getAppInfosSort() {
        List<PackageInfo> packages = RunTimeApplication.getCurApp().getPackageManager().getInstalledPackages(0);
        if (packages == null)
            return null;
        List<ApkBean> beans = new ArrayList<>();
        HashMap<Long, PackageInfo> mHashMap = new HashMap<Long, PackageInfo>();
        for (PackageInfo info : packages) {
            if ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                mHashMap.put(info.lastUpdateTime, info);//如果非系统应用，则添加至appList
            }
        }

        List<Map.Entry<Long, PackageInfo>> mHashMapEntryList = new ArrayList<Map.Entry<Long, PackageInfo>>(mHashMap.entrySet());
        Collections.sort(mHashMapEntryList, new Comparator<Map.Entry<Long, PackageInfo>>() {

            @Override
            public int compare(Map.Entry<Long, PackageInfo> firstMapEntry,
                               Map.Entry<Long, PackageInfo> secondMapEntry) {
                return firstMapEntry.getKey().compareTo(secondMapEntry.getKey());
            }
        });
        for (Map.Entry<Long, PackageInfo> entry : mHashMapEntryList) {
            PackageInfo packageInfo = entry.getValue();
            String appName = packageInfo.applicationInfo.loadLabel(RunTimeApplication.getCurApp().getPackageManager()).toString();
            String packageName = packageInfo.packageName;
            String versionName = packageInfo.versionName;
            if(RunTimeApplication.getCurApp().getPackageName().equals(packageName))
                continue;
            int versionCode = packageInfo.versionCode;
            Drawable appIcon = packageInfo.applicationInfo.loadIcon(RunTimeApplication.getCurApp().getPackageManager());
            beans.add(new ApkBean(appName, appIcon,versionCode,versionName,packageName));
        }
        return beans;

    }




    /**
     * 卸载一个app
     */
    public static void uninstall(Context context, String packageName) {
        //通过程序的包名创建URI
        Uri packageURI = Uri.parse("package:" + packageName);
        //创建Intent意图
        Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
        if(intent!=null){
            //执行卸载程序
            context.startActivity(intent);
        }else
            ToastUtil.show("未找到应用程序");
    }

    /**
     * 获取已安装非系统应用
     *
     * @return
     */
    public static List<ApkBean> scanInstallApp(Context mContext) {
        List<ApkBean> appInfos = new ArrayList<>();
        PackageManager pm = mContext.getPackageManager(); // 获得PackageManager对象
        List<ApplicationInfo> listAppcations = pm
                .getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
        Collections.sort(listAppcations,
                new ApplicationInfo.DisplayNameComparator(pm));// 字典排序
        for (ApplicationInfo app : listAppcations) {
            if ((app.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {//非系统程序
                appInfos.add(getAppInfo(app, pm));
            }//本来是系统程序，被用户手动更新后，该系统程序也成为第三方应用程序了
            else if ((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
                appInfos.add(getAppInfo(app, pm));
            }
        }
        return appInfos;
    }

    /**
     *  构造一个AppInfo对象 ，并赋值
     */
    private static ApkBean getAppInfo(ApplicationInfo app, PackageManager pm) {
        ApkBean appInfo = new ApkBean();
        appInfo.name=pm.getApplicationLabel(app).toString();//应用名称
        appInfo.icon = app.loadIcon(pm);//应用icon
        appInfo.packageName = app.packageName ;//应用包名，用来卸载
        File file = new File(app.sourceDir);
        float size = file.length();
        DecimalFormat df = new DecimalFormat("#.00");
        appInfo.size = df.format(size / (1024 * 1024)) + "M";//应用大小，M单位，保留两位小数
        PackageInfo packageInfo = null;
        try {
            packageInfo = pm.getPackageInfo(app.packageName, 0);
            appInfo.lastUpdateTime= packageInfo.lastUpdateTime;//应用最近一次更新时间
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appInfo;
    }

    public static void openApk(Context ctx,String packageName){
        PackageManager packageManager = ctx.getPackageManager();
        Intent it = packageManager.getLaunchIntentForPackage(packageName);
        if (it != null)
            ctx.startActivity(it);
        else
            ToastUtil.show("未找到应用程序");
    }

}
